import 'dart:async';

import 'package:flutter_chat_ui/pages/chat_room_controller.dart';
import 'package:flutter_chat_ui/utils/audio_utils.dart';
import 'package:flutter_chat_ui/utils/utils.dart';
import 'package:get/get.dart';

///
/// 语音相关 - 优化版本，减少UI重建和卡顿
///
class VoiceController extends GetxController {
  static VoiceController get to => Get.find<VoiceController>();

  /// 进行语音录制状态
  final voiceStatus = VoiceStatus.idle.obs;

  /// 语音转文本
  final voiceToText = ''.obs;

  /// 防抖定时器
  Timer? _statusUpdateTimer;
  Timer? _textUpdateTimer;

  /// 状态缓存，避免不必要的更新
  VoiceStatus? _cachedStatus;
  String? _cachedText;

  @override
  void onClose() {
    // 清理定时器
    _statusUpdateTimer?.cancel();
    _textUpdateTimer?.cancel();

    super.onClose();
  }

  ///
  /// 防抖更新录制语音状态 - 关键优化点
  ///
  void _updateStatusWithDebounce(VoiceStatus value) {
    // 如果状态没有变化，直接返回
    if (_cachedStatus == value) return;

    _statusUpdateTimer?.cancel();
    _statusUpdateTimer = Timer(const Duration(milliseconds: 16), () {
      // 约60fps的更新频率
      if (_cachedStatus != value) {
        _cachedStatus = value;
        voiceStatus.value = value;
      }
    });
  }

  ///
  /// 防抖更新语音转文本 - 减少频繁的UI更新
  ///
  void _updateTextWithDebounce(String text) {
    // 如果文本没有变化，直接返回
    if (_cachedText == text) return;

    _textUpdateTimer?.cancel();
    _textUpdateTimer = Timer(const Duration(milliseconds: 100), () {
      // 减少文本更新频率
      if (_cachedText != text) {
        _cachedText = text;
        voiceToText.value = text;
      }
    });
  }

  ///
  /// 直接更新录制语音状态（无防抖）- 用于需要立即响应的场景
  ///
  void updateStatus(VoiceStatus value) {
    if (_cachedStatus != value) {
      _cachedStatus = value;
      voiceStatus.value = value;
    }
  }

  ///
  /// 发送信息
  ///
  void sendVoiceToText() {
    if (Utils.isBlank(voiceToText.value)) {
      return;
    }

    // 异步发送消息，避免阻塞UI
    Future.microtask(() {
      ChatRoomController.to.sendMessage(
        voiceToText.value,
        conversationId: Utils.lastConversationId ?? '',
      );
    });

    // 清空缓存和状态
    _cachedText = '';
    voiceToText.value = '';
  }

  ///
  /// 重置状态 - 用于清理
  ///
  void reset() {
    _statusUpdateTimer?.cancel();
    _textUpdateTimer?.cancel();
    _cachedStatus = null;
    _cachedText = null;
    voiceStatus.value = VoiceStatus.idle;
    voiceToText.value = '';
  }
}
